''' <summary>
''' Class to provide importing of LSPC AIR files; FileName is full path to last active AIR file; TableName will include list of all filenames (w/o extension) in same directory (analogous to station ID)
''' </summary>
Public Class clsDataLspcAir
    Inherits clsDataLspcOut

    ''' <summary>
    ''' Instantiate clsDataLSPCAir
    ''' </summary>
    ''' <param name="_FileName">Name of text file to read</param>
    Public Overrides Sub Initialize(ByVal _FileName As String)
        MyBase.Initialize(_FileName)
        mDataType = enumDataType.LspcAir
    End Sub

    ''' <summary>
    ''' Instantiate and get list of parameter names (note that entire line after first two characters will be set as field name, including parameter name, description, and units); good stuff always starts in column 6 of header
    ''' </summary>
    ''' <param name="_FileName">Name of LSPC OUT file to read</param>
    Friend Overrides Sub Open(ByVal _FileName As String)
        If Not My.Computer.FileSystem.FileExists(_FileName) Then
            Throw New ApplicationException("The LSPC Air file was not found: " & _FileName)
            Exit Sub
        End If
        mFilename = _FileName
        mRecordNum = -1
        If sr IsNot Nothing Then sr.Close() : sr.Dispose()
        sr = New IO.StreamReader(_FileName, System.Text.Encoding.ASCII, False, cBufferSize)
        mFileLength = sr.BaseStream.Length

        'get fieldnames from header of first AIR file found (or leave empty)
        mFieldNames.Clear()

        mLastLineRead = ""
        Do
            mLastLineRead = sr.ReadLine
            If mLastLineRead.Length >= 2 Then mLastLineRead = mLastLineRead.Substring(2).Trim
            If sr.EndOfStream Then
                sr.Close()
                sr.Dispose()
                Throw New ApplicationException("Unable to find constituent names in " & _FileName)
                Exit Sub
            End If
        Loop Until mLastLineRead.StartsWith("Label       ")
        mFieldNames.Add("Station_ID")
        mFieldNames.Add("Date_Time")
        mLastLineRead = sr.ReadLine
        If mLastLineRead.Length >= 2 Then mLastLineRead = mLastLineRead.Substring(2).Trim
        Do While mLastLineRead <> ""
            Dim PCode As String = mLastLineRead.Substring(0, 24).Trim  'grab first 24 characters
            mFieldNames.Add(PCode)
            mPCodes.Add(PCode)
            mLastLineRead = sr.ReadLine
            If mLastLineRead.Length >= 2 Then mLastLineRead = mLastLineRead.Substring(2).Trim
        Loop

        'skip past rest of header records to start of data (which is 2nd line after date/time record)
        Do While Not (mLastLineRead.ToUpper.Contains("DATE/TIME") And mLastLineRead.ToUpper.Contains("VALUES")) And Not sr.EndOfStream
            mLastLineRead = sr.ReadLine
        Loop
        sr.ReadLine()

    End Sub

    ''' <summary>
    ''' Read next line from file into memory
    ''' </summary>
    ''' <returns>True if successful</returns>
    Public Overrides Function Read() As Boolean
        Try
            If Not MyBase.Read() Then Return False
            If sr.EndOfStream Then 'go to next station ID
                If mActiveStationIDSet Then
                    Return False 'only read one stationid
                Else
                    Dim idx As Integer = mStationIDs.IndexOf(mActiveStationID)
                    If idx = mStationIDs.Count - 1 Then
                        Return False
                    Else
                        ActiveStationID = mStationIDs(idx + 1)
                        mActiveStationIDSet = False 'to keep it going
                    End If
                End If
            End If

            'data line looks like this:
            '7     1996 12 31 24  0            0.            0.           32.            0.            0.          29.5            0.

            With sr
                If .EndOfStream Then Return False
                mLastLineRead = .ReadLine
                Dim ar() As String = mLastLineRead.Split(New Char() {" ", vbTab}, StringSplitOptions.RemoveEmptyEntries)
                If ar.Length <> mFieldNames.Count + 4 Then Throw New Exception("The AIR file has an invalid format; the last line read was: " & mLastLineRead) : Return False
                mItems.Clear()
                mItems.Add(IO.Path.GetFileNameWithoutExtension(mFilename)) 'station id
                Dim hr As Integer = ar(4)
                If hr = 24 Then
                    'must convert to date (is slow) then add a day
                    Dim dt As Date = New Date(ar(1), ar(2), ar(3), 0, ar(5), 0)
                    dt = dt.AddDays(1)
                    mItems.Add(dt.ToString("MM/dd/yyyy HH:mm"))
                Else
                    mItems.Add(String.Format("{0}/{1}/{2} {3:00}:{4:00}", ar(2), ar(3), ar(1), hr, ar(5))) 'date as string
                End If
                For i As Integer = 6 To ar.Length - 1
                    mItems.Add(ar(i)) 'all other pcodes=2..n
                Next
                Return True
            End With

        Catch ex As Exception
            ErrorMsg(, ex)
            Return False
        End Try

    End Function

    ''' <summary>
    ''' Read next line from file into memory (faster method that only reads date and single column
    ''' </summary>
    ''' <returns>True if successful</returns>
    Friend Overrides Function ReadItem(ByVal ItemNum As Integer, ByRef DateTime As Date, ByRef Result As Single) As Boolean
        Try
            If Not MyBase.Read() Then Return False
            If sr.EndOfStream Then 'go to next station ID
                If mActiveStationIDSet Then
                    Return False 'only read one stationid
                Else
                    Dim idx As Integer = mStationIDs.IndexOf(mActiveStationID)
                    If idx = mStationIDs.Count - 1 Then
                        Return False
                    Else
                        ActiveStationID = mStationIDs(idx + 1)
                        mActiveStationIDSet = False 'to keep it going
                    End If
                End If
            End If

            With sr
                If .EndOfStream Then Return False
                mLastLineRead = .ReadLine
                Dim ar() As String = mLastLineRead.Split(New Char() {" "}, StringSplitOptions.RemoveEmptyEntries)
                If ar.Length <> mFieldNames.Count + 4 Then Throw New Exception("The AIR file has an invalid format; the last line read was: " & mLastLineRead) : Return False
                Dim hr As Integer = ar(4)
                If hr = 24 Then 'must add a day
                    DateTime = New Date(ar(1), ar(2), ar(3), 0, ar(5), 0)
                    DateTime = DateTime.AddDays(1)
                Else
                    DateTime = New Date(ar(1), ar(2), ar(3), hr, ar(5), 0)
                End If
                Result = ar(ItemNum + 6)
                Return True
            End With
            Return True
        Catch ex As Exception
            ErrorMsg(, ex)
            Return False
        End Try

    End Function

    Public Overrides ReadOnly Property MaxDate() As Date
        Get
            Rewind()
            Dim lastdate As Date = CDate("1/1/1901")
            While Read()
                lastdate = mItems(1)
            End While
            Return lastdate
        End Get
    End Property

End Class
